<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="ui comments"  th:fragment="comments">
    <h3 class="ui dividing header">评论</h3>
    <div class="comment" th:if="${comments}" th:each="comment : ${comments}">
        <a class="author" th:text="${comment.username}"></a>
        <div class="metadata">
            <span class="date" th:text="${comment.createTime}"></span>
        </div>
        <div class="text" th:text="${comment.comment}"></div>
        <div class="ui divider"></div>
    </div>
    <div  th:if="not ${comments}">
        还没有评论~赶紧来抢沙发~
    </div>
</div>
<div class="ui" th:fragment="addComment">
    <form class="ui form addcomment" method="post" action="/comment">
        <div class="ui error message"></div>
        <input type="hidden" name="newsId" id="newsId" th:value="${news.id}"/>
        <div class="field">
            <textarea name="comment" id="commentText" cols="30" rows="10"></textarea>
        </div>
        <div class="field">
            <div class="ui primary submit button">回复</div>
        </div>
        <input type="hidden" th:if="${_csrf}" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
    </form>
    <script>
        $(document).ready(function() {
            $('.ui.form.addcomment').form({
                onSuccess: function () {
                    var formData = {
                        newsId: $("#newsId").val(),
                        comment: $("#commentText").val()
                    };

                    $.ajax({
                        headers:{'X-CSRF-TOKEN':$("input[name=_csrf]").val()},
                        type: 'POST',
                        url: '/comment',
                        contentType: "application/json",
                        data: JSON.stringify(formData),
                        success: onFormSubmitted,
                        error: errormsg
                    });
                }
            }).submit( function( e ) {
                e.preventDefault();
            });
            function getFieldValue(fieldId) {
                // 'get field' is part of Semantics form behavior API
                return $('.ui.form.edit').form('get field', fieldId).val();
            }
            function errormsg(err) {
                $('.ui.form.addcomment').form('add errors',[err]);
            }
            // Handle post response
            function onFormSubmitted(response) {
                console.log(response)
                if(response=='ok'){
                    window.location.reload();
                }else{
                    $('.ui.form.addcomment').form('add errors',[response]);
                }
            }
        });

    </script>
</div>

</body>

</html>